package org.jspar.model;

import org.jspar.Constants;
import org.jspar.tile.Position;


public class Terminal {
	
	public static final int RIGHT = 0;
	public static final int DOWN  = 1;
	public static final int LEFT  = 2;
	public static final int UP    = 3;
	

	private String name;
	private int side;
	private Position position;
	private Module module;
	private Net net;
	private Direction type;

	public Terminal(Module module, String name, int side, Direction type, int xPos, int yPos) {
		this.name = name;
		this.net = null;
		this.side = side;
		this.position = new Position(xPos, yPos);
		this.type = type;
		this.module = module;
	}
	
	public boolean isOut() {
		return type == Direction.OUT;
	}
	
	public boolean isInOut() {
		return type == Direction.INOUT;
	}
	
	public boolean isIn() {
		return type == Direction.IN;
	}

	
	public String name() { return name; }
	public Module module() { return module; }
	public Net net() { return net; }
	public Direction type() { return type; }
	
	void setNet(Net net) {
		this.net = net;
	}

	public int side() { return side; }
	public int x() { return position.x(); }
	public int y() { return position.y(); }
	
	public Position getPosition() {
		return position;
	}
	
	public void setPosition(int x, int y) {
		this.position = new Position(x, y);
	}
	
	public Position getGlobalPosition() {
		return position.add(module.getPosition());
	}
	
	public void rotate(int r) {

		int xOld = position.x();    
		int yOld = position.y();
	
		switch(r) {
			case Module.R90:
				position = new Position(yOld, module.width() - xOld);
				break;
				
			case Module.R180:
				position = new Position(module.width() - xOld, module.height() - yOld);
				break;
				
			case Module.R270:
				position = new Position(module.height() - yOld, xOld);
				break;
		}
		side = (side + r) % 4;
	}

	public void applyModel(TerminalModel model) {
		position = model.position();
		side = model.side();
	}
	
	public Position terminalSpacer() {
		int x = 0;
		if (side() == Terminal.RIGHT)
			x = Constants.TERM_MARGIN;
		if (side() == Terminal.LEFT)
			x = -Constants.TERM_MARGIN;

		int y = 0;
		if (side() == Terminal.UP)
			y = Constants.TERM_MARGIN;
		if (side() == Terminal.DOWN)
			y = -Constants.TERM_MARGIN;
		return new Position(x, y);
	}

	public int terminalSpacer(int axis) {
		if (axis == Constants.X) {
			if (side() == Terminal.RIGHT)
				return Constants.TERM_MARGIN;
			if (side() == Terminal.LEFT)
				return -Constants.TERM_MARGIN;
		} else if (axis == Constants.Y) {
			if (side() == Terminal.UP)
				return Constants.TERM_MARGIN;
			if (side() == Terminal.DOWN)
				return -Constants.TERM_MARGIN;
		}
		return 0;
	}

	@Override
	public String toString() {
		return module.toString() + "." + name;
	}
	
}
